const jwt = require('jsonwebtoken');
module.exports = () => {
    return async (ctx,next) => {
        console.log("====中间件")
        //1.过滤不需要校验接口
        let writePath = ['/api/login','/api/registry'];
        if(writePath.includes(ctx.path)){
            //有 不用校验
            await next();
        }else{
            //需要校验
            console.log(ctx.headers.token)
            let token = ctx.headers.token;
            //jwt.verify(token,'1810b')
            try{
                //token校验
                let info = jwt.verify(token,'1801b');
                console.log(info,"=====");
                ctx.info = info;
                await next();
            }catch(e){
                //token  JsonWebTokenError：token  TokenExpiredError:过期
                //区分错误
                if(e.name === 'JsonWebTokenError' || e.name === 'TokenExpiredError'){
                    //401
                    ctx.status = 401;
                    ctx.body = {
                        code:4,
                        msg:e
                    }
                }else{
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }
    }
}